package com.runfast.common.restdoc.snippet;

import capital.scalable.restdocs.javadoc.JavadocReader;
import capital.scalable.restdocs.javadoc.JavadocReaderImpl;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

public class DefaultJavadocReader implements JavadocReader {
    private JavadocReaderImpl javadocReader = null;

    {
        javadocReader = JavadocReaderImpl.createWithSystemProperty();
    }

    @Override
    public String resolveFieldComment(Class<?> javaBaseClass, String javaFieldName) {
        return javadocReader.resolveFieldComment(javaBaseClass, javaFieldName);
    }

    @Override
    public String resolveFieldTag(Class<?> javaBaseClass, String javaFieldName, String tagName) {
        return javadocReader.resolveFieldTag(javaBaseClass, javaFieldName, tagName);
    }

    @Override
    public String resolveMethodComment(Class<?> javaBaseClass, String javaMethodName) {
        return javadocReader.resolveMethodComment(javaBaseClass, javaMethodName);
    }

    @Override
    public String resolveMethodParameterComment(Class<?> javaBaseClass, String javaMethodName, String javaParameterName) {
        return javadocReader.resolveMethodParameterComment(javaBaseClass, javaMethodName, javaParameterName);
    }

    @Override
    public String resolveMethodTag(Class<?> javaBaseClass, String javaMethodName, String tagName) {
        return javadocReader.resolveMethodTag(javaBaseClass, javaMethodName, tagName);
    }

    public String resolveClassComment(Class<?> javaBaseClass) {
        Method classJavadocMethod = ReflectionUtils.findMethod(JavadocReaderImpl.class, "classJavadoc", Class.class);
        classJavadocMethod.setAccessible(true);
        Object classJavadoc = ReflectionUtils.invokeMethod(classJavadocMethod, javadocReader, javaBaseClass);

        Method getClassCommentMethod = ReflectionUtils.findMethod(classJavadoc.getClass(), "getClassComment");
        getClassCommentMethod.setAccessible(true);
        Object classComment = ReflectionUtils.invokeMethod(getClassCommentMethod, classJavadoc);
        return classComment != null ? classComment.toString() : "";
    }
}
